export default{
	
	namespaced: true,
	
	state:()=>({
		//购物车的数组
		//每个商品的信息
		//包括{ goods_id , goods_name , goods_price , goods_count , goods_small_logo , goods_state }
		cart: JSON.parse(uni.getStorageSync('cart')||'[]')
	}),
	
	mutations:{
		
		addToCart(state,goods){
			//没有商品result为undefine
			const result = state.cart.find((x)=>x.goods_id===goods.goods_id)
			
			if(!result){
				state.cart.push(goods)
			}else{
				result.goods_count++
			}
			
			this.commit('m_cart/saveToStorage')
		},
		
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		
		//更新勾选状态
		updateState(state,goods){
			//state.cart为未更改状态前
			const result = state.cart.find(x=>x.goods_id===goods.goods_id)
			if(result){
				result.goods_state = goods.goods_state
				//更改storage的数据
				this.commit('m_cart/saveToStorage')
			}
			
		},
		
		updateCount(state,goods){
			const result = state.cart.find(x=>x.goods_id===goods.goods_id)
			if(result){
				result.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
			
		},
		
		removeGoods(state,goods_id){
			state.cart = state.cart.filter(x=>x.goods_id!==goods_id)
			this.commit('m_cart/saveToStorage')
			
		},
		//全选或全不选
		updateCheck(state,newState){
			state.cart.forEach(x=>x.goods_state=newState)
			this.commit('m_cart/saveToStorage')
		}
	},
	
	getters:{
		//统计购物车总数量
		total(state){
			let c = 0
			
			state.cart.forEach(x=>c += x.goods_count)
			//用reduce方法
			// c =  state.cart.reduce((total,item)=>total+=item.goods_count,0)
			
			return c
		},
		//计算总数量
		checkedCount(state){
			//先用filter过滤判断是否勾选
			//再用reduce返回勾选的总数量total
			//item指过滤后的数组
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
		},
		price(state){
			return state.cart.filter(x=>x.goods_state).
					reduce((total,item)=>total+=item.goods_count*item.goods_price,0).
					toFixed(2)
		}
	}
}